package com.sky.service.impl;

import com.sky.dto.AdminLoginDTO;
import com.sky.exception.BaseException;
import com.sky.entity.Admin;
import com.sky.mapper.AdminMapper;
import com.sky.service.AdminService;
import com.sky.utils.JwtUtil;
import org.springframework.util.DigestUtils;
import com.sky.vo.AdminLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Value("${sky.jwt.admin-secret-key}")
    private String adminSecretKey;

    @Value("${sky.jwt.admin-ttl}")
    private Long adminTtl;

    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        // 1. 根据用户名查询管理员
        Admin admin = adminMapper.selectByUsername(username);

        // 2. 验证密码
        if (admin == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 对输入密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!admin.getPassword().equals(encryptedPassword)) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 3. 更新最后登录时间
        adminMapper.updateLastLoginTime(admin.getId(), LocalDateTime.now());

        // 4. 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("username", admin.getUsername());
        claims.put("role", admin.getRole());
        String token = JwtUtil.createJWT(adminSecretKey, adminTtl, claims);

        // 5. 构建并返回登录结果VO
        return AdminLoginVO.builder()
                .id(admin.getId())
                .username(admin.getUsername())
                .name(admin.getName())
                .role(admin.getRole())
                .token(token)
                .lastLoginTime(admin.getLastLoginTime())
                .build();
    }

    @Override
    public void logout() {
        // 无状态JWT认证，服务端无需特殊处理
        // 客户端删除token即可
    }

    @Override
    public Map<String, Object> selectByPage(Map<String, Object> map) {
        // 计算分页参数
        int page = (int) map.get("page");
        int pageSize = (int) map.get("pageSize");
        int start = (page - 1) * pageSize;

        // 设置分页参数
        map.put("start", start);
        map.put("pageSize", pageSize);

        // 查询管理员列表
        List<Admin> adminList = adminMapper.selectByPage(map);

        // 查询管理员总数
        Integer total = adminMapper.selectCount(map);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("records", adminList);
        result.put("total", total);

        return result;
    }

    @Override
    public void insert(Admin admin) {
        // 检查用户名是否已存在
        Admin existingAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (existingAdmin != null) {
            throw new BaseException("用户名已经存在！");
        }

        // 对密码进行MD5加密
        String encryptedPassword = DigestUtils.md5DigestAsHex(admin.getPassword().getBytes());
        admin.setPassword(encryptedPassword);

        // 设置创建时间和更新时间
        admin.setCreatedAt(LocalDateTime.now());
        admin.setUpdatedAt(LocalDateTime.now());

        // 插入管理员
        adminMapper.insert(admin);
    }

    @Override
    public Admin selectById(Long id) {
        return adminMapper.selectById(id);
    }

    @Override
    public void update(Admin admin) {
        // 设置更新时间
        admin.setUpdatedAt(LocalDateTime.now());

        // 更新管理员信息
        adminMapper.update(admin);
    }

    @Override
    public void updatePassword(Long adminId, String oldPassword, String newPassword) {
        // 查询管理员
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 验证旧密码
        String encryptedOldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!admin.getPassword().equals(encryptedOldPassword)) {
            throw new RuntimeException("旧密码错误");
        }

        // 对新密码进行MD5加密
        String encryptedNewPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());

        // 更新密码
        adminMapper.updatePassword(adminId, encryptedNewPassword);
    }

    @Override
    public void updateStatus(Long id, String status) {
        adminMapper.updateStatus(id, status);
    }

    @Override
    public void deleteById(Long id) {
        // 查询管理员
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            throw new RuntimeException("管理员不存在");
        }

        // 检查是否为super角色
        if ("super".equals(admin.getRole())) {
            throw new RuntimeException("不能删除超级管理员");
        }

        // 删除管理员
        adminMapper.deleteById(id);
    }
}